<template>
  <div class="teacher-experiments">
    <el-card>
      <div style="display: flex; justify-content: space-between; align-items: center;">
        <span style="font-size: 20px; font-weight: bold;">我的实验</span>
        <el-button type="primary" @click="showCreateDialog = true">新建实验</el-button>
      </div>
      <el-table
        :data="experiments"
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        border
      >
        <el-table-column prop="name" label="实验名称" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            {{ categories.find(item => item.value === row.category)?.label || row.category }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="difficulty" label="难度" width="130">
          <template #default="{ row }">
            <el-rate 
            :model-value="Number(row.difficulty)" 
            disabled 
            show-text 
            :texts="['简单', '初级', '中等', '困难', '挑战']" 
            />
          </template>
        </el-table-column>
        
        <el-table-column label="时间范围" width="180">
          <template #default="{ row }">
            <div v-if="row.start_time || row.end_time">
              <div>开始: {{ formatDate(row.start_time) }}</div>
              <div>结束: {{ formatDate(row.end_time) }}</div>
            </div>
            <span v-else>未设置</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="140">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="goToDetail(row.id)">查看</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <!-- 实验对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建实验" width="600px">
      <el-form :model="createForm" :rules="formRules" ref="createFormRef" label-width="100px">
        <el-form-item label="实验名称" prop="name">
          <el-input v-model="createForm.name" />
        </el-form-item>
        <el-form-item label="实验分类" prop="category">
          <el-select v-model="createForm.category" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-rate
            v-model="createForm.difficulty"
            :max="5"
            show-text
            :texts="['简单', '初级', '中等', '困难', '挑战']"
          />
        </el-form-item>
        
        <el-form-item label="实验时间" prop="timeRange">
          <el-date-picker
            v-model="createForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="createForm.tags"
            multiple
            filterable
            allow-create
            placeholder="请输入标签"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="createForm.description" type="textarea" :rows="4" />
        </el-form-item>
        <el-form-item label="实验材料">
          <el-upload
            v-model:file-list="createForm.files"
            action="/api/upload/"
            multiple
            :limit="5"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">支持上传PDF/Word/PPT等文档，不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="实验任务" prop="tasks">
          <el-select
            v-model="createForm.tasks"
            multiple
            filterable
            placeholder="请选择实验任务"
          >
            <el-option
              v-for="task in taskOptions"
              :key="task.id"
              :label="task.name"
              :value="task.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="阅读材料" prop="reading_materials">
          <el-select
            v-model="createForm.reading_materials"
            multiple
            filterable
            placeholder="请选择阅读材料"
          >
            <el-option
              v-for="item in readingMaterialOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">创建</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()
const goToDetail = (id) => {
  router.push(`/experiments/${id}`)
}

const experiments = ref([])
const loading = ref(false)
const showCreateDialog = ref(false)
const createFormRef = ref(null)
// 添加日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '未设置';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');
}
const categories = ref([
  { value: 'physics', label: 'Python实验' },
  { value: 'chemistry', label: 'OS实验' },
  { value: 'biology', label: 'SQL实验' },
  { value: 'computer', label: '计算机实验' },
])
console.log(experiments.value)
const createForm = reactive({
  name: '',
  category: '',
  difficulty: 3,
  timeRange: [],
  tags: [],
  description: '',
  files: [],
  tasks:[],
  reading_materials: []
})
const taskOptions = ref([])
const readingMaterialOptions = ref([])
const formRules = {
  name: [{ required: true, message: '请输入实验名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择实验分类', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  timeRange: [{ required: true, message: '请选择实验时间范围', trigger: 'change' }],
  tasks: [{ required: true, message: '请选择实验任务', trigger: 'change' }] 
}
const fetchReadingMaterials = async () => {
  try {
    const res = await axios.get('/api/reading-materials/')
    readingMaterialOptions.value = res.data
  } catch (e) {
    ElMessage.error('获取阅读材料失败')
  }
}
const handleDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除该实验吗？此操作不可撤销。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.delete(`/api/teacher/experiments/${id}/`)
      ElMessage.success('删除成功')
      fetchExperiments()
    } catch (e) {
      ElMessage.error('删除失败: ' + (e.response?.data?.message || e.message))
    }
  }).catch(() => {})
}
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

const fetchExperiments = async () => {
  loading.value = true
  try {
    const res = await axios.get('/api/teacher/experiments/')
    console.log('API Response:', res.data)
    if (res.data && res.data.results) {
      experiments.value = res.data.results
    } else if (Array.isArray(res.data)) {
      experiments.value = res.data
    } else {
      experiments.value = []
    }
    console.log('Experiments:', experiments.value)
  } catch (e) {
    ElMessage.error('获取实验列表失败')
  } finally {
    loading.value = false
  }
}
const fetchTasks = async () => {
  try {
    const res = await axios.get('/api/tasks/')
    taskOptions.value = res.data
  } catch (e) {
    ElMessage.error('获取任务列表失败')
  }
}

onMounted(() => {
  fetchExperiments()
  fetchTasks() 
  fetchReadingMaterials()
})
const submitCreate = () => {
  createFormRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const formData = new FormData()
      formData.append('name', createForm.name)
      formData.append('category', createForm.category)
      formData.append('difficulty', createForm.difficulty)
      formData.append('start_time', createForm.timeRange[0]?.toISOString())
      formData.append('end_time', createForm.timeRange[1]?.toISOString())
      formData.append('tags', JSON.stringify(createForm.tags))
      formData.append('description', createForm.description)
      
      createForm.files.forEach(file => {
        formData.append('files', file.raw)
      })
      
      // 修改这里 - 直接传递数组，不要用 JSON.stringify
      createForm.tasks.forEach(taskId => {
        formData.append('task_ids', taskId)
      })
      createForm.reading_materials.forEach(id => {
        formData.append('reading_material_ids', id)
      })
      await axios.post('/api/teacher/experiments/', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      ElMessage.success('创建成功')
      showCreateDialog.value = false
      fetchExperiments()
      resetForm()
    } catch (e) {
      console.error('后端返回错误:', e.response?.data)
      ElMessage.error('创建失败: ' + (e.response?.data?.message || e.message))
    }
  })
}

const resetForm = () => {
  createFormRef.value?.resetFields()
  createForm.files = []
}


</script>

<style scoped>
.teacher-experiments {
  max-width: 900px;
  margin: 32px auto;
}
</style>